package com.Lixiaoqian.PartyHistoryMuseum.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.Lixiaoqian.PartyHistoryMuseum.R;
import com.Lixiaoqian.PartyHistoryMuseum.base.MyApplication;
import com.Lixiaoqian.PartyHistoryMuseum.bean.BannerBean;
import com.Lixiaoqian.PartyHistoryMuseum.inface.ArchitectViewHolderInterface;
import com.Lixiaoqian.PartyHistoryMuseum.net.ApiConstant;
import com.Lixiaoqian.PartyHistoryMuseum.utils.Constant;
import com.Lixiaoqian.PartyHistoryMuseum.utils.PlayMusic;
import com.Lixiaoqian.PartyHistoryMuseum.view.RBeatLoadView;
import com.wikitude.architect.ArchitectView;
import com.wikitude.architect.StartupConfiguration;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class ArCamActivity extends AbstractArchitectCamActivity implements ArchitectView.ArchitectUrlListener {
    private static String TAG = ArCamActivity.class.getName();
    @BindView(R.id.iv_sao_bg)
    ImageView ivSaoBg;
    @BindView(R.id.iv_switch)
    Switch ivSwitch;
    @BindView(R.id.tv_tishi)
    TextView tvTishi;
    @BindView(R.id.ll_tishi)
    LinearLayout llTishi;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.ll_playMusic_bar)
    LinearLayout llPlayMusic;
    @BindView(R.id.btn_stop)
    ImageView btnStop;
    @BindView(R.id.loadView)
    RBeatLoadView loadView;
    @BindView(R.id.rl_top_bar)
    RelativeLayout rlTopBar;
    @BindView(R.id.music_title)
    TextView musicTitle;
    @BindView(R.id.rl_buttom_bar)
    RelativeLayout rlButtomBar;
    private long lastCalibrationToastShownTimeMillis = System.currentTimeMillis();
    private PlayMusic playMusic;
    private Timer timer = new Timer();
    private AudioManager audioManaget;
    private String musicName;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        permissionChecker.checkPsOpen(this, Constant.PERMISS_CAMERA);
        playMusic = new PlayMusic();
        audioManaget = (AudioManager) getSystemService(AUDIO_SERVICE);
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.iv_resao, R.id.iv_help, R.id.btn_stop, R.id.loadView, R.id.iv_voice_inc, R.id.iv_voice_dis, R.id.iv_voice_close})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_resao:
                ResetScan();
                break;
            case R.id.iv_help:
                WebActivity.launch(this, ApiConstant.HELP_URL);
                break;
            case R.id.btn_stop:
                if (!playMusic.mediaPlayer.isPlaying()) {
                    loadView.setVisibility(View.VISIBLE);
                    btnStop.setVisibility(View.GONE);
                    playMusic.start();
                }
                break;
            case R.id.loadView:
                if (playMusic.mediaPlayer.isPlaying()) {
                    loadView.setVisibility(View.GONE);
                    btnStop.setVisibility(View.VISIBLE);
                    playMusic.pause();
                }
                break;
            case R.id.iv_voice_inc:
                audioManaget.adjustVolume(AudioManager.ADJUST_RAISE, 0);
                break;
            case R.id.iv_voice_dis:
                audioManaget.adjustVolume(AudioManager.ADJUST_LOWER, 0);
                break;
            case R.id.iv_voice_close:
                ResetScan();
                rlButtomBar.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * 重置扫描
     */
    private void ResetScan() {
        this.onReset();
        recognizeChangeUI("扫描中...", View.VISIBLE);
        llPlayMusic.animate().scaleX(0).start();
        playMusic.stop();
    }

    @Override
    protected StartupConfiguration.CameraPosition getCameraPosition() {
        return StartupConfiguration.CameraPosition.DEFAULT;
    }

    @Override
    public ArchitectView.ArchitectUrlListener getUrlListener() {
        return this;
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_ar_cam;
    }


    @Override
    public String getWikitudeSDKLicenseKey() {
        return Constant.WIKITUDE_KEY;
    }

    @Override
    public int getArchitectViewId() {
        return R.id.architectView;
    }

    @Override
    public ArchitectView.SensorAccuracyChangeListener getSensorAccuracyListener() {
        return new ArchitectView.SensorAccuracyChangeListener() {
            @Override
            public void onCompassAccuracyChanged(int accuracy) {
                /* UNRELIABLE = 0, LOW = 1, MEDIUM = 2, HIGH = 3 */
                if (accuracy < SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM && ArCamActivity.this != null && !ArCamActivity.this.isFinishing() && System.currentTimeMillis() - ArCamActivity.this.lastCalibrationToastShownTimeMillis > 5 * 1000) {
                    ArCamActivity.this.lastCalibrationToastShownTimeMillis = System.currentTimeMillis();
                }
            }
        };
    }


    @Override
    public void initIntent() {

    }

    @Override
    public void initButton() {
        /**闪光灯开关*/
        ivSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                architectView.setFlashEnabled(isChecked);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            Toast.makeText(this, "请允许打开摄像头", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    public float getInitialCullingDistanceMeters() {
        return ArchitectViewHolderInterface.CULLING_DISTANCE_DEFAULT_METERS;
    }

    @Override
    public boolean urlWasInvoked(String s) {
        Uri invokedUri = Uri.parse(s);
        switch (invokedUri.getHost()) {
            case "onPlayStard"://开始播放视频
                recognizeChangeUI("识别成功", View.GONE);
                break;
            case "onVideoDownload":                  //开始下载视频
                String videoName = invokedUri.getQueryParameter("videoName");
                for (BannerBean bean : MyApplication.bannerDataList.getData()) {
                    if (bean.getSourcename().equals(videoName)) {
                        new VideoDownUtils(Constant.SAVE_VIDEO_PATH, videoName + ".mp4").execute(ApiConstant.IMAGE_BASE_URL + bean.getContent_file());
                        break;
                    }
                }
                break;
            case "onPlayVoive":
                String voiceName = invokedUri.getQueryParameter("voiceName");
                File file = new File(Constant.VOICE_PATH, voiceName + ".mp3");
                if (!file.exists()) {
                    for (BannerBean bean : MyApplication.voiceDataList.getData()) {
                        if (bean.getSourcename().equals(voiceName)) {
                            new VideoDownUtils(Constant.VOICE_PATH, voiceName + ".mp3").execute(ApiConstant.IMAGE_BASE_URL + bean.getContent_file());
                            break;
                        }
                    }
                } else {
                    recognizeChangeUI("识别成功", View.GONE);
                    for (BannerBean bean : MyApplication.voiceDataList.getData()) {
                        if (bean.getSourcename().equals(voiceName)) {
                            musicTitle.setText(bean.getSourcedesc());
                            musicTitle.setVisibility(View.VISIBLE);
                            break;
                        } else {
                            musicTitle.setVisibility(View.GONE);
                        }
                    }
                    rlButtomBar.setVisibility(View.GONE);
                    llPlayMusic.setVisibility(View.VISIBLE);
                    llPlayMusic.animate().scaleX(1).start();
                    playMusic.playMusic(file.getAbsolutePath());
                    seekBar.setMax(playMusic.mediaPlayer.getDuration());
                    loadView.setVisibility(View.VISIBLE);
                    btnStop.setVisibility(View.GONE);
                    showProgressBar();
                }
                break;
        }
        return true;

    }

    /**
     * 根据识别状态改变ui
     *
     * @param tishi_info
     * @param flag
     */
    private void recognizeChangeUI(String tishi_info, int flag) {
        tvTishi.setText(tishi_info);
        rlTopBar.setVisibility(flag);
        ivSaoBg.setVisibility(flag);
    }

    /**
     * 实时进度条显示
     */
    private void showProgressBar() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    if (playMusic.mediaPlayer != null && playMusic.mediaPlayer.isPlaying()) {
                        int currentPosition = playMusic.mediaPlayer.getCurrentPosition();
                        seekBar.setProgress(currentPosition);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 0, 50);
    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        playMusic.onDestory();
    }

    public static void launch(Activity activity) {
        activity.startActivity(new Intent(activity, ArCamActivity.class));
    }

    /**
     * 识别后视频下载类
     */
    public class VideoDownUtils extends AsyncTask<String, Integer, String> {
        private String savePath;
        private String saveFileName;

        public VideoDownUtils(String savePath, String saveFileName) {
            this.savePath = savePath;
            this.saveFileName = saveFileName;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            File file = new File(savePath);
            if (!file.exists()) { //创建文件路径
                file.mkdir();
            }
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                downFile(params[0]);
            } catch (IOException e) {
                //  ToastUtils.showShort(App.getContext(),"下载失败");
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            // ToastUtils.showShort(App.getContext(),"下载完成");
            downFileFinish();
            tvTishi.setText("识别中...");
        }

        /**
         * Runs on the UI thread after {@link #publishProgress} is invoked.
         * The specified values are the values passed to {@link #publishProgress}.
         *
         * @param values The values indicating progress.
         * @see #publishProgress
         * @see #doInBackground
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            tvTishi.setText("正在下载资源:" + values[0]);
        }

        /**
         * 下载zip文件逻辑
         *
         * @throws IOException
         * @downUrl 下载地址
         */
        private void downFile(String downUrl) throws IOException {
            //连接地址
            URL url = new URL(downUrl);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            int lenghtOfFile = c.getContentLength();//计算长度
            c.connect();
            FileOutputStream f = new FileOutputStream(new File(savePath, saveFileName));
            InputStream in = c.getInputStream();
            //下载的代码
            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; //total = total + len1
                publishProgress((int) ((total * 100) / lenghtOfFile));
                f.write(buffer, 0, len1);
            }
            f.close();
        }
    }
}
